/*
 * 
 * 
 */

/*
 * JDialogUnsteg.java
 *
 * Created on 2009-08-12, 10:27:26
 */

package steg.gui.unsteg;

import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker.StateValue;
import steg.steki.PlikSteg;
import steg.steki.StegException;
import steg.sekret.UnSekret;
import steg.utils.MojaLinkedHashMap;

/**
 *
 * @author Tryllion
 */
public abstract class JDialogUnsteg extends javax.swing.JDialog {

    protected static String PATH_LST_OPEN = "C:\\BUCKUP\\Teraz\\SVN\\plikiTestowe\\"; // ostatnio otwarta scierzka w JFileChooser
    protected static final String PLIK_STEG_EXTENCION = ".unsteg.";

    private boolean isPlikLoaded =false;

    // stegi
    protected UnSekret sekret; //pusty kontener na sekret
    protected PlikSteg plikStegowany;

    /** Creates new form JDialogUnsteg */
    public JDialogUnsteg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        setLocationRelativeTo(null);
        initComponents();
        initStartOpcje();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButtonStart = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jPasswordField1 = new javax.swing.JPasswordField();
        jCheckBox3 = new javax.swing.JCheckBox();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();

        jButton2.setText("jButton2");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zimg/avi64.png"))); // NOI18N
        jButton1.setToolTipText("załaduj plik");
        jButton1.setMargin(new java.awt.Insets(2, 1, 2, 1));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jProgressBar1.setMaximum(1000);

        jLabel1.setFont(new java.awt.Font("Arial", 1, 24));
        jLabel1.setForeground(new java.awt.Color(68, 30, 30));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("wyszukaj w MPO");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButtonStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zimg/start.png"))); // NOI18N
        jButtonStart.setEnabled(false);
        jButtonStart.setMargin(new java.awt.Insets(2, 1, 2, 1));
        jButtonStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStartActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel3.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jPanel3PropertyChange(evt);
            }
        });

        jCheckBox1.setText("GZIP");
        jCheckBox1.setToolTipText("wiadomośc zostanie skompresowana");

        jCheckBox2.setText("haslo");
        jCheckBox2.setToolTipText("hasło programu, nie pliku GZIP");
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        jPasswordField1.setEnabled(false);

        jCheckBox3.setSelected(true);
        jCheckBox3.setText("tag");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "8", "4", "2", "1" }));

        jLabel3.setText("Bitów na bajt");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jCheckBox1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox3, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jCheckBox2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(2, 2, 2)
                                .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBox2)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(60, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonStart))
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(162, 162, 162)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonStart)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        // TODO add your handling code here:
        jPasswordField1.setEnabled(jCheckBox2.isSelected() );
}//GEN-LAST:event_jCheckBox2ActionPerformed

    //load plik
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //pusty model
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {}
        },
                new String [] {

        }
        ));

        isPlikLoaded = true; // na error trzeba wygasic
        loadUnStegPlik();

        czyMoznaGo();
    }//GEN-LAST:event_jButton1ActionPerformed

    // start
    private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed

        try {

            //zablokowac i ustawic na 0 all
            this.setEnabled(false);
            jProgressBar1.setValue(0);

            // przypisać śledzący aparat :D
            plikStegowany.addComponentWithChangeListener( jPanel3 );
            plikStegowany.setMaxProgressValue( jProgressBar1.getMaximum() );


            // 2 nazwanie unpaczki
            // nazwa pliku, dziala to tak cos.exe ->> cos.PLIK_STEG_EXTENCION.exe
            String nazwa = plikStegowany.getFile().getPath();
            if(nazwa.indexOf(".")==-1)nazwa += ".steg"; // jkesli ni ma roszerzenia, bo durny error bedzie
            String nazwaPocz = nazwa.substring( 0, nazwa.lastIndexOf(".") );
            nazwa = nazwaPocz + PLIK_STEG_EXTENCION /*+ nazwa.substring( nazwaPocz.length()+1, nazwa.length() )*/;//bez rozszerzenia

            UnSekret unpaczka = new UnSekret( new File(nazwa));

            unpaczka.setBitowNaSample( getBitowNaSample() );
            unpaczka.setCzyZnacznik( czyTag());
    //        unpaczka.setCzyGZip( czyGZIP());
            unpaczka.setCzyHaslo( czyHaslo());
            if(unpaczka.isCzyHaslo())
                unpaczka.setSekretHaslo( getHaslo());

            unsteganuj();

            // amoze wspolne unsteguj ??? !
            plikStegowany.unsteg(unpaczka);

            zakoncz();
            
        } catch (StegException ex) {

            raportError(ex,"mp3 niepoprawna");
            JOptionPane.showMessageDialog(this, ex.getStegMassage(),"Błąd steganograficzny!",
                    JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
            raportError(ex,"błąd wczytu mp3");
            JOptionPane.showMessageDialog(this, "Błąd wczytania pliku.","Błąd pliku!",
                    JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            //error nie znany, lepiej wypłapywać wszystko, potem można jak co czeknąć co jest 5
            raportError(ex,"błąd przy próbie wczytu "+this.getTitle() );
            JOptionPane.showMessageDialog(this, "Błąd wczytania pliku.","Błąd!!!",
                    JOptionPane.ERROR_MESSAGE);

        }finally {
            this.setEnabled(true);
        }

    }//GEN-LAST:event_jButtonStartActionPerformed

    // zmieniacz proprryty
    private void jPanel3PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jPanel3PropertyChange
        

        // ustaw progres
        if ("progress".equals(evt.getPropertyName()))
            jProgressBar1.setValue( (Integer) evt.getNewValue());


        // KONIEC
        if (evt.getNewValue() == StateValue.DONE  ) {

            // czy były błedy ?
            StegException sex= plikStegowany.throwException();
            if(sex!=null) {
                raportError(sex,"Błąd steganografii");
                JOptionPane.showMessageDialog(this, sex.getStegMassage(),"Błąd odzyskiwania.",
                        JOptionPane.ERROR_MESSAGE);
                JOptionPane.showMessageDialog(this, "Proces nie został zakończony.\nProszę zmienić parametry i spróbować ponownie.","Uwaga!",
                        JOptionPane.WARNING_MESSAGE);
                jProgressBar1.setValue( jProgressBar1.getMaximum() );

            }else{
                Toolkit.getDefaultToolkit().beep(); // DZWIEK :D
                JOptionPane.showMessageDialog(this, "Proces został zakończony","Koniec.",
                        JOptionPane.INFORMATION_MESSAGE);
            }

            zakoncz(); // ostatnie sprawy
            jButtonStart.setEnabled(false);
            this.setEnabled(true);


        }


    }//GEN-LAST:event_jPanel3PropertyChange


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonStart;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void czyMoznaGo() {
        if(!isPlikLoaded) {jButtonStart.setEnabled(false); return;}

        jProgressBar1.setValue(0);
        jButtonStart.setEnabled(true);
    }

    /**
     * Wstawia dane do estetycznej tabelki.
     * @param metaDane
     */
    protected void setMetaDane(MojaLinkedHashMap metaDane) {

        jTable1.setModel(metaDane.getDefaultTableModel());

    }

    /**
     * Raportuje o błędach.
     * Funkcja do zmiany, trzeba ją ujednolicić dla całego GUI.
     *
     * @param ex
     */
    protected void raportError(Exception ex, String opis) {

        // aby wszystko bylo w jednym miejscu, blad takze tu obslugujemy
        /**
         * MYślę że to dobry pomysł, bo różne błedy trzeba będzie różnie obsłużyć
         * Na razie mam 2, więc wydaje się to nie potrzebne, ale cholera wie jak to
         * będzie w przyszłości, zostawiam taki dziwny mechanizm
         *
         */
        isPlikLoaded = false;

        System.out.println("------------- Raport o błędzie:\n"+opis);
        Logger.getLogger(JDialogUnsteg.class.getName()).log(Level.SEVERE, null, ex);
    }

    /*opcje opcji , ustawianie czy sa dostepne, nie selected i takie tam !!!!*/
    protected void setIsGZIP(boolean v, boolean b, boolean set) {
        jCheckBox1.setVisible(v);
        jCheckBox1.setEnabled(b);
        jCheckBox1.setSelected(set);
    }
    protected void setIsHaslo(boolean v, boolean b, boolean set) {
        jCheckBox2.setVisible(v);
        jPasswordField1.setVisible(v);
        jCheckBox2.setEnabled(b);
        jPasswordField1.setEnabled(b);
        jCheckBox2.setSelected(set);

    }
    protected void setIsTag(boolean v, boolean b, boolean set) {
        jCheckBox3.setVisible(v);
        jCheckBox3.setEnabled(b);
        jCheckBox3.setSelected(set);
    }


    protected boolean czyGZIP() {
        return jCheckBox1.isSelected();
    }
    protected boolean czyHaslo() {
        return jCheckBox2.isSelected();
    }
    protected boolean czyTag() {
        return jCheckBox3.isSelected();
    }
    protected char[] getHaslo() {
        return jPasswordField1.getPassword();
    }
    protected int getBitowNaSample() {
        return Integer.parseInt( (String) jComboBox1.getSelectedItem());
    }


    /* czemu init? bardziej dlatego są tak ponazywane i podzielone aby pamietac nizby jakis z tego mial byc uzytek*/
    /**
     * Tytuł nagłówka jak i całej ramki.
     * @param str
     */
    protected void initTilte(String str) {
        this.setTitle(str);
        jLabel1.setText(str);
    }
    protected void initPlikIcon(String str) {
        try{
            jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zimg/"+str)));
        }catch(NullPointerException ex) {
            raportError(ex,"brak pliku->"+str);
        }
    }

    protected abstract void initStartOpcje();

    /*konkrety różne dla każdego rodzaju steganografi*/
    protected abstract void loadUnStegPlik();
    protected abstract void unsteganuj() throws StegException, IOException;
    protected abstract void zakoncz() /*throws StegException, IOException*/;

}
